package com.demo.reflection.utils;

import com.demo.reflection.demo1.domain.User;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class PropertyUtil {

        public int[] twoSum(int[] nums, int target) {
            Map<Integer, Integer> map = new HashMap();
            for (int i = 0; i < nums.length; i++) {
                if (map.containsKey(target - nums[i])) {
                    return new int[]{i, map.get(i)};
                }
                map.put(nums[i], i);
            }
            throw new RuntimeException("no matched numbers");
        }

    public static Map<String, String> diffUser(User old, User newone) {
        Map<String, String> diffMap = new HashMap<>();
        if ((old.getId() == null && newone.getId() != null) ||
                (old.getId() != null && !(old.getId()==newone.getId()))
        ) {
            diffMap.put("id", "from " + old.getId() + " to " + newone.getId());
        }
        return diffMap;
    }

    /**
     * 用于比较任意类型的实例属性
     * @param old
     * @param newObj
     * @return
     */
    public static Map<String, String> diffObj(Object old, Object newObj) {
        Map<String, String> diffMap = new HashMap<>();
        try {
            Class oldObjClazz = old.getClass();
            Class newObjClazz = newObj.getClass();
            if (oldObjClazz.equals(newObjClazz)) {
                // 获取对象的所有属性
                Field[] fields = oldObjClazz.getDeclaredFields();
                // 对每个属性逐一判断
                for (Field field : fields) {
                    //使属性可以被反射访问
                    field.setAccessible(true);
                    //获取当前属性的值
                    Object oldValue = field.get(old);
                    Object newValue = field.get(newObj);
                    if ((oldValue == null && newValue != null) || (oldValue != null && !oldValue.equals(newValue))) {
                        diffMap.put(field.getName(), "from " + oldValue + " to " + newValue);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return diffMap;
    }
}
